package com.example.jpa.service.impl;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.model.User;
import com.example.jpa.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by liulanhua on 2018/3/21.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> findAll()
    {
        return userRepository.findAll();
    }

    @Override
    public List<User> findByName(String name)
    {
        User user = new User();
        user.setName(name);
        Example<User> userExample = Example.of(user);
        return userRepository.findAll(userExample);
        //return userRepository.findByName(name);
    }

    @Override
    @Transactional
    public void saveUser(User user)
    {
        userRepository.save(user);
    }

    @Cacheable("users")
    @Override
    public User findOne(String id)
    {
        User user = new User();
        user.setId(id);
        Example<User> userExample = Example.of(user);
        return userRepository.findOne(userExample).orElse(null);
    }

    @Override
    @Transactional
    public void delete(String id)
    {
        userRepository.deleteById(id);
    }

}
